/**
 * 
 */
package net.toocruel.iqismart.service.impl;

import net.toocruel.iqismart.entity.rbac.User;
import net.toocruel.iqismart.service.RbacService;
import net.toocruel.iqismart.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author toocruel
 *
 */
@Component("rbacService")
public class RbacServiceImpl implements RbacService {

	private AntPathMatcher antPathMatcher = new AntPathMatcher();

	@Autowired
	private UserService userService;

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Override
	@Transactional
	public boolean hasPermission(HttpServletRequest request, Authentication authentication) {

		logger.info(request.getRequestURL().toString());

		Object principal = authentication.getPrincipal();

		AtomicBoolean hasPermission = new AtomicBoolean(false);

		String requestURI = request.getRequestURI();

//		Set<String> annyList = new HashSet<>();
//		annyList.add("/question/[0-9]+");
//		if(request.getMethod().equals(HttpMethod.GET.name())){
//			annyList.stream().forEach(reg->{
//				if(Pattern.compile(reg).matcher(requestURI).find()){
//					hasPermission.set(true);
//				}
//			});
//		}
//
//		if(hasPermission.get()){
//			return hasPermission.get();
//		}

		if (principal instanceof User) {
			//如果用户名是admin，就永远返回true
			if (StringUtils.equals(((User) principal).getUsername(), "admin")) {
				hasPermission.set(true);
			} else {
				// 读取用户所拥有权限的所有URL
				User user = userService.findById(((User) principal).getId());
//				user.getRoles().stream().forEach(role -> {
//					role.getResources().stream().forEach(resource -> {
//						 //
//					});
//				});
				Set<String> urls = user.getUrls();
				for (String url : urls) {
					if (antPathMatcher.match(url, requestURI)) {
						hasPermission.set(true);
						break;
					}
				}
			}

			//认证用户可以访问除/admin/**外的链接
			if(!hasPermission.get()){
				if(!requestURI.startsWith("/admin")){
					hasPermission.set(true);
				}
			}
		}



		return hasPermission.get();
	}

}
